<?php
/**
 * 推送信息
 * Created by wzb.
 * User: wzb
 * time:2017/08/23
 */

/************处理订单信息*******************/
/**接收数据的参数名 items
*
*/
//require("interface.php");


require("interface.php");

//同步订单


$sql_order = "select * from dlz_order_info where increment_id='M000026781'";
$query_order = $db->query($sql_order);//返回影响了多少行数据
$row_orders = $query_order->fetchAll(PDO::FETCH_ASSOC);
foreach ($row_orders as $key => $row_order) {
//while($row_order = $query_order->fetch()){
        $postarrary = array();
        $shopId = "mall00".$row_order['store_id'];//高清未按照约定 处理的字段
        //$shopId = "OFFLINE6";
        $orderId = $row_order['increment_id'];
        echo " ******************$orderId****************\n";
        $status = $row_order['status'];//订单状态 WAIT_SELLER_SEND_GOODS WAIT_BUYER_ACCEPT_GOODS FINISH
        if($status == "complete"){
            $orderStatus = "FINISH";
        }elseif($status == "processing") {
             $orderStatus = "WAIT_SELLER_SEND_GOODS";//WAIT_BUYER_ACCEPT_GOODS
        }
        
        $base_total_paid_str = $row_order['base_total_paid'];//pay_success pay_closed 付款状态
        $base_total_paid = Number_format($base_total_paid_str, 2, '.','');
        $Netamount = Number_format($row_order['Net_amount'], 2, '.','');
        if(empty($base_total_paid_str)){
              $loanStatus = "pay_closed";
        }else{
              $loanStatus = "pay_success";
        }

        $created_at = $row_order['created_at'];
        $gmtCreate_str=date('YmdHisz',strtotime($created_at));
        $gmtCreate = $gmtCreate_str."-0700";  //高清未按照约定 处理的字段
        //$gmtCreate = $gmtCreate_str;
        $updated_at = $row_order['updated_at'];
        $gmtModified_str=date("YmdHisz",strtotime($updated_at));
        $gmtModified = $gmtModified_str."-0700";//高清未按照约定 处理的字段
        //$gmtModified = $gmtModified_str;
        $gmtPaySuccess = $gmtCreate;
       // $base_grand_total = $row_order['base_grand_total'];
        $base_grand_total_str = $row_order['base_grand_total'];
        $base_grand_total = Number_format($base_grand_total_str, 2, '.','');
        $order_currency_code = $row_order['order_currency_code'];
        $base_shipping_amount_str = $row_order['base_shipping_amount'];
        $base_shipping_amount = Number_format($base_shipping_amount_str, 2, '.','');

        $payment_method = $row_order['payment_method'];//WU PP WeChatPay Alipay BankTransfer  
        $billNo = $row_order['payment_last_trans_id'];
        $statuss = PostApi_($postarrary,$shopId,$orderId,$status,$orderStatus,$base_total_paid,$Netamount,$loanStatus,$created_at,$gmtCreate,$gmtModified,$gmtPaySuccess,$base_grand_total,$order_currency_code,$base_shipping_amount,$payment_method,$billNo,$db);
        if($statuss == '4'){
          echo '我遇到假死的。。。';
        }
}
function PostApi_($postarrary,$shopId,$orderId,$status,$orderStatus,$base_total_paid,$Netamount,$loanStatus,$created_at,$gmtCreate,$gmtModified,$gmtPaySuccess,$base_grand_total,$order_currency_code,$base_shipping_amount,$payment_method,$billNo,$db){
  //获取店铺信息
  $sql_store = "select thirduser,thirdpwd from dlz_account_info where thirdname='$shopId'";
  $query_store = $db->query($sql_store);//返回影响了多少行数据
  while($row_store = $query_store->fetch()){
      $loginName = base64_encode($row_store['thirduser']);
      $password = base64_encode($row_store['thirdpwd']);
  }

  $postarrary['loginName'] = "$loginName";
  $postarrary['password'] = "$password";
    //付款信息
  $postarrary['requestEntity']['shopId'] = "$shopId";
  $postarrary['requestEntity']['orderId'] = "$orderId";
  $postarrary['requestEntity']['orderStatus'] = "$orderStatus";
  $postarrary['requestEntity']['loanStatus'] = "$loanStatus";
  $postarrary['requestEntity']['gmtCreate'] = "$gmtCreate";
  $postarrary['requestEntity']['gmtModified'] = "$gmtModified";
  $postarrary['requestEntity']['gmtPaySuccess'] = "$gmtPaySuccess";


  //在此处解决推送时，出现订单不全问题，可能是网络延迟，导致拿到的信息不全导致的某个子订单滞后。此处拿产品id做个判断
  //同一产品 相同id 下单不同尺寸，导致推送 不完全，带解决
$check_order_num = "select distinct product_id from dlz_attribute_all_id where increment_id='$orderId'";
$query_check_order_num = $db->query($check_order_num);//返回影响了多少行数据
$firstnumber = count($query_check_order_num->fetchAll());
print_r($firstnumber);
echo $firstnumber."\n";
$check_order_num2 = "select distinct product_id from dlz_order_product where increment_id='$orderId'";
$query_check_order_num2 = $db->query($check_order_num2);//返回影响了多少行数据
$secondnumber = count($query_check_order_num2->fetchAll());
echo $secondnumber."\n";
echo "------------$firstnumber:$secondnumber----------- \n";
//$sql_product = "select * from dlz_post_orderinfo where increment_id='$orderId'";

if("$firstnumber" == "$secondnumber"){
    $sql_product = "select * from dlz_post_orderinfo where increment_id='$orderId'";
    $ordernumberquestion = 'yes';
}else{
    $ordernumberquestion = 'no';
    $sql_product = "select * from dlz_post_orderinfo where increment_id=''";
}
    //echo "$sql_product \n";
    $query_product = $db->query($sql_product);//返回影响了多少行数据
    $num = 0;
    $densityMemo=null;
    $densityMemoPost = array();
  while($row_product = $query_product->fetch()){
    $id = $row_product['child_id'];
    $productId = $row_product['product_id'];
    $category = $row_product['category'];
    $color = $row_product['color'];
    $grade = $row_product['grade'];
    $style_str = $row_product['texture'];//Kinky Straight  不被识别
    if(strpos("$style_str",'Body') !== false){
        $style = "Body";
    }else if(strpos("$style_str",'Deep') !== false){
        $style = "Deep";

    }else if (strpos("$style_str",'Curly') !== false){
        $style = "Kinky Curly";
    //}else if (strpos("$style_str",'Straight') !== false){
    }else if (strpos("$style_str",'Straight') !== false && strpos("$style_str",'Hair') !== false){
        $style = "Straight";
    }else{
        $style = $style_str;
    }

// 修正 ，有些 国家带 hair  有些不带，并且修正一些拼写错误  /首字母大写
    $humanHairType_str = ucfirst(trim($row_product['type_country']));
    if(strpos("$humanHairType_str",'Hair') !== false){
        $humanHairType = $humanHairType_str;
    }else{
        $humanHairType = $humanHairType_str.' '.'Hair';
    }
    if(strpos("$humanHairType",'Malaysian') !== false){
      $humanHairType = "Malaysia Hair";// 与速卖通平台保持一致
    }

    $size = $row_product['inch'].'inch';
    $type = $row_product['type'];//待定Lace Closure Silk Base Closure Lace Frontal Silk Base Frontal

    $hairDesign = $row_product['hairDesign'];
    $capSize_str = $row_product['capSize'];
    //修正发冒大小
    if(strpos("$capSize_str",'Small') !== false){
        $capSize = "Small";
    }else if(strpos("$capSize_str",'Medium') !== false){
        $capSize = "Medium";
    }else if(strpos("$capSize_str",'Large') !== false){
        $capSize = "Large";
    }else if(strpos("$capSize_str",'Average') !== false){
        $capSize = "Average Size";
    }else{
        $capSize = $capSize_str;
    }
    $laceWigType = $row_product['laceWigType'];
    $density_str = $row_product['density'];//不接收 % 号。报错 400
    $density = str_replace('%',' ',$density_str);
    $lacesize = $row_product['laceSize'];
    $lotNum = $row_product['lotNum'];
    $productCount = $row_product['productCount'];
    //$currencyCode = $row_product['currencyCode'];
    $amount = $row_product['amount'];
    //产品信息
    $child_amount = Number_format(0, 2, '.','');
    $postarrary['requestEntity']['childOrderList'][$num] = array(
                              'id' => "$id",
                              'productId' => "$productId",
                              'productOwnerMemberId' => "$shopId",
                              'category' => "$category",
                              'color' => "$color",
                              'grade' => "$grade",
                              'humanHairType' => "$humanHairType",
                              'size' => "$size",
                              'style' => "$style",
                              'type' => "$type",
                              'hairDesign' => "$hairDesign",
                              'capSize' => "$capSize",
                              'laceWigType' => "$laceWigType",
                              'density' => "$density",
                              'lacesize' => "$lacesize",
                              'lotNum' => "$lotNum",
                              'productCount' => "$productCount",
                              'initAmt' => array(
                                'amount' => "$child_amount",
                                'currencyCode' => "$order_currency_code"
                                )

    ); 
    $num++;
      //处理密度  2017 12 22

    $postarrary['requestEntity']['memo1']=null;

    if($density >= '150'){
     $densityMemoPost[$id] = $id.'的密度：'.$density.' ';
    }
   // $densityMemoPost[$id] = $densityMemo;

     /*  $densityMemo = null;
    if($density >= '150'){
      $densityMemo = '密度：'.$density;
     // $postarrary['requestEntity']['memo1'] = $densityMemo;
    }*/
    }//产品循环结束  




    /*
    $postarrary['requestEntity']['buyerInfo']['country'] = 'US';
    $postarrary['requestEntity']['buyerInfo']['email'] = 'abc@aa.com';
    $postarrary['requestEntity']['buyerInfo']['loginId'] = 'us123213343';
    $postarrary['requestEntity']['buyerInfo']['firstName'] = 'Jerry';
    $postarrary['requestEntity']['buyerInfo']['lastName'] = 'Wang';
    */
   //买家信息
   
$sql_buyer = "select * from dlz_shipping_info where increment_id ='$orderId'";
$query_buyer = $db->query($sql_buyer);//返回影响了多少行数据
while($row_buyer = $query_buyer->fetch()){
        $country_str = $row_buyer['country_id'];
        if($country_str == 'GB'){
          $country = 'UK';
        }else{
          $country = $country_str;
        }//英国不被识别，需转下。

        $email = $row_buyer['email'];
        $loginId = $row_buyer['entity_id'];
        $firstName = $row_buyer['firstname'];
        $lastName = $row_buyer['lastname'];
        $address_str = $row_buyer['shipping_street'];
      // if(strlen($address_str) <= 35){
       //   $address = $address_str;
       // }else{
          $address_arr = explode("__",$address_str);
          $address = $address_arr[0];
          $address2 = !empty($address_arr[1])?$address_arr[1] : '';
          //$address = "Unknown(The address is too long)";
       // }
        $zip = $row_buyer['postcode'];
        $mobileNo_str = $row_buyer['telephone'];
      if(!empty($mobileNo_str)){
          $mobileNo = findNum($str="$mobileNo_str");//调用正则 识别号码
        }/*  else{
          $mobileNo = "Unknown";
        }*/
        $detailAddress = $row_buyer['shipping_street'];
        $city = $row_buyer['city'];
        $province = $row_buyer['region'];



  $postarrary['requestEntity']['buyerInfo'] = array(
                            'country' => "$country",
                            'email' => "$email",
                            'loginId' => "$loginId",//待定
                            'firstName' => "$firstName",//待确认 位置
                            'lastName' => "$lastName"

  );
  $buyerSignerFullname = $firstName.' '.$lastName;
  $postarrary['requestEntity']['buyerLoginId'] = "$loginId";
  $postarrary['requestEntity']['buyerSignerFullname'] = "$buyerSignerFullname";

  $postarrary['requestEntity']['orderAmount'] = array(
                            'amount' => "$base_grand_total",
                            'currencyCode' => "$order_currency_code"

  );
  $postarrary['requestEntity']['logisticsAmount'] = array(
                            'amount' => "$base_shipping_amount",
                            'currencyCode' => "$order_currency_code"

  );
  $postarrary['requestEntity']['realloanAmount'] = array(
                            'amount' => "$Netamount",
                            'currencyCode' => "$order_currency_code"

  );
  if("$payment_method" == "paypal_express") {
    $payment_method_str = "PP";
  }else{
    $payment_method_str = "BankTransfer";
  }
  $postarrary['requestEntity']['paymentType'] = "$payment_method_str";
  $postarrary['requestEntity']['billNo'] = "$billNo";


  
  $postarrary['requestEntity']['receiptAddress'] = array(
                            'address' => $address,
                            'address2' => $address2,
                            'city' => "$city",
                            'contactPerson' => "$buyerSignerFullname",
                            'country' => "$country",//GB 英国不被识别
                            'detailAddress' => "$address",
                            'faxArea' => '',
                            'faxCountry' => '',
                            'faxNumber' => '',
                            'mobileNo' => " $mobileNo",
                            'phoneArea' => '',
                            'province' => "$province",
                            'zip' => "$zip"

  );
  //处理备注内容，系统默认
  $sql_memo = "select memo from dlz_order_product where increment_id='$orderId' and memo != ''";
  $query_memo = $db->query($sql_memo);//返回影响了多少行数据
  $memoPost = null;
  while($row_memo = $query_memo->fetch()){
      $memoPost = $row_memo['memo'];
  }
  $desmeo = implode(' ',$densityMemoPost);//分割预先准备好的备注
  $postarrary['requestEntity']['memo1'] = $memoPost.' '.$desmeo;
    //$postarrary['requestEntity']['memo1'] = $memoPost.' '.$densityMemo;
 }

//判断是否有产品


//$zuzhaungjson = array('parameter' =>$postarrary );
//$jsonStr = json_encode($zuzhaungjson);
$zuzhaungjson = json_encode($postarrary);
$jsonStr = $zuzhaungjson;
//
$storeid = $postarrary['requestEntity']['shopId'];
echo "$jsonStr"."\n";
$getStatus = list($returnCode, $returnContent) = http_post_json($jsonStr,$db,$orderId,$storeid,$ordernumberquestion);
if($getStatus == '4'){
  return $statuss='4';
}
//request_post($data=$postarrary,$orderId,$db); 
//echo "$returnCode \n $returnContent";
}
 



function get_millisecond(){
    list($usec, $sec) = explode(" ", microtime());
    $msec=round($usec*1000);
    return $msec;
}
function http_post_json($jsonStr,$db,$orderId,$storeid,$ordernumberquestion)
{
  $url = "http://rxyhair.com:8081/ryterp/orderinfo/createOrder";
  $ch = curl_init($url);
  //curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
  curl_setopt($ch, CURLOPT_TIMEOUT, 60);
  curl_setopt($ch, CURLOPT_POSTFIELDS, 'parameter='.$jsonStr);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_HEADER, 0);
  $data = curl_exec($ch);
  $data_arr = json_decode($data, TRUE);
  //print_r($data_arr);
  if(!empty($data_arr)){
  $code = $data_arr['code'];
  $detailedDecription = addslashes($data_arr['detailedDecription']);
  $UpdateTime = date('Y-m-d H:i:s');
  $post_status_arrary = array();
  $post_status_arrary['code'] =  $code;
  $post_status_arrary['orderId'] =  $orderId;
  $post_status_arrary['detailedDecription'] =  $detailedDecription;
  $post_status_arrary['updatetime'] =  $UpdateTime;
  $post_status_arrary['storeid'] =  $storeid;
  //记录post
  Getinsert($arrData=$post_status_arrary,$table='dlz_post_record_status',$db,$sync_data="0");
  if("$code" == "0"){//记录成功
      $insert_status = "update dlz_order_info set post_status='1' where increment_id='$orderId'";//post成功 修改状态
      $db->exec($insert_status);
  }elseif(strpos($detailedDecription,'重复添加') !== false){
      $insert_status = "update dlz_order_info set post_status='1' where increment_id='$orderId'";//重复post 修改状态
      $db->exec($insert_status);
  }else{
        $insert_statu = "update dlz_attribute_all_id set sync_status='0' where increment_id='$orderId'";//post 失败，致 订单产品同步状态 为失败
        $db->exec($insert_statu);
        $insert_statu_p = "update dlz_order_product set option_status='0' where increment_id='$orderId'";//post 失败，致 订单产品同步状态 为失败
        $db->exec($insert_statu_p);
  }
  }else{
  $code = '2';
  $detailedDecription = addslashes($data);
  $UpdateTime = date('Y-m-d H:i:s');
  $post_status_arrary = array();
  $post_status_arrary['code'] =  $code;
  $post_status_arrary['orderId'] =  $orderId;
  /*
  if($ordernumberquestion = 'no'){
    $post_status_arrary['detailedDecription'] =  '订单不全,等下个推送时间段会自动更新';
  }else{
    if(strpos($detailedDecription,'HTTP Status 500') !== false){
      $post_status_arrary['detailedDecription'] =  '产品做过修改，请手动同步';
    }else{
      $post_status_arrary['detailedDecription'] =  $detailedDecription;
    }
    
  }
  */
 /******处理推送失败的状态******/
 if(strpos($detailedDecription,'HTTP Status 500') !== false){
  $check_sku = "select sku from dlz_attribute_all_id where increment_id='$orderId'";
  $query_sku = $db->query($check_sku);//返回影响了多少行数据
  $rows = $query_sku->fetch();
  if(strpos($rows['sku'],'差价') !== false){//判断sku是否为差价
      $post_status_arrary['detailedDecription'] =  '差价';
  }else{
      $post_status_arrary['detailedDecription'] =  '订单产品不存在，建议手写单！';
  }

 }elseif ($ordernumberquestion = 'no') {
   $post_status_arrary['detailedDecription'] =  '订单不全,等下个推送时间段会自动更新';
 }else{
      $status2 = '4';//给个状态，防止假死
      $post_status_arrary['detailedDecription'] =  $detailedDecription;
  }
// $post_status_arrary['detailedDecription'] =  $detailedDecription;
  $post_status_arrary['updatetime'] =  $UpdateTime;
  $post_status_arrary['storeid'] =  $storeid;
  //记录post
  Getinsert($arrData=$post_status_arrary,$table='dlz_post_record_status',$db,$sync_data="0");
   $insert_statu_Y = "update dlz_order_product set option_status='1' where increment_id='$orderId'";
    $checkStatus = $db->exec($insert_statu_Y);//如果出现 400 500，则不在推送。storeid
    if(isset($status2) && $checkStatus){
      return $status2;
    }
  }
  curl_close($ch);
  //print_r($data);
}

// 只匹配数字
function findNum($str=''){
        $str=trim($str);
        if(empty($str)){return '';}
        $temp=array('1','2','3','4','5','6','7','8','9','0');
        $result='';
        for($i=0;$i<strlen($str);$i++){
            if(in_array($str[$i],$temp)){
                $result.=$str[$i];
            }
        }
        return $result;
    }


$db = null;
exit;
